﻿#region copyright
// Halcyone - Silverlight Application Framework
// Copyright (C) 2009 - 2010 Alexey Zakharov (B&Z LLC)
// 
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Mvc;

namespace Witcraft.Halcyone.ASPFacility
{
    /// <summary>
    /// 
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class RestServiceAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            AddQuerystringToRouteData(filterContext);

            ParseComplexParameters(filterContext);

            if ((filterContext.HttpContext.Request.ContentType ?? string.Empty)
                .Contains("application/json"))
            {
                InjectRequestParameter(filterContext);
            }
        }

        private static bool CheckRequestParameter(IEnumerable<ParameterDescriptor> parameters)
        {
            int requestParamAttributeCount = 0;
            requestParamAttributeCount =
                parameters.Aggregate(
                    requestParamAttributeCount,
                    (s, p) =>
                        {
                            if (p.IsDefined(typeof (RequestParameterAttribute), false))
                            {
                                return ++s;
                            }
                            return s;
                        });

            if (requestParamAttributeCount > 1)
            {
                throw new ArgumentException("You declared more than 1 request attribute");
            }

            return requestParamAttributeCount > 0;
        }

        private static void InjectRequestParameter(
            ActionExecutingContext filterContext)
        {
            ParameterDescriptor[] parameterDescriptors = filterContext.ActionDescriptor.GetParameters();

            if (CheckRequestParameter(parameterDescriptors))
            {
                ParameterDescriptor parameterDescriptor = parameterDescriptors
                    .Single(p => p.IsDefined(typeof (RequestParameterAttribute), false));

                object parameterValue = new DataContractJsonSerializer(parameterDescriptor.ParameterType)
                    .ReadObject(filterContext.HttpContext.Request.InputStream);

                filterContext.ActionParameters[parameterDescriptor.ParameterName] = parameterValue;
            }
        }

        private static bool IsPrimitive(Type type)
        {
            return type.IsPrimitive || type == typeof (string) || type == typeof (DateTime) || type == typeof (Decimal);
        }

        private static void ParseComplexParameters(ActionExecutingContext filterContext)
        {
            IEnumerable<ParameterDescriptor> parameterDescriptors = filterContext.ActionDescriptor
                .GetParameters()
                .Where(
                    p => !IsPrimitive(p.ParameterType) && filterContext.RouteData.Values.Keys.Contains(p.ParameterName));

            foreach (ParameterDescriptor parameterDescriptor in parameterDescriptors)
            {
                var jsonString = filterContext.RouteData.Values[parameterDescriptor.ParameterName] as string;

                if (jsonString != null)
                {
                    using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
                    {
                        object parameterValue =
                            new DataContractJsonSerializer(parameterDescriptor.ParameterType).ReadObject(stream);
                        filterContext.ActionParameters[parameterDescriptor.ParameterName] = parameterValue;
                    }
                }
            }
        }

        private static void AddQuerystringToRouteData(ActionExecutingContext filterContext)
        {
            NameValueCollection nameValueCollection = filterContext.HttpContext.Request.QueryString;

            foreach (string key in nameValueCollection.AllKeys)
            {
                filterContext.RouteData.Values.Add(key, nameValueCollection[key]);
            }
        }
    }
}